package com.yanzhang.dao.role;

import com.yanzhang.pojo.Role;
import com.yanzhang.util.DBUtil;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yanzhang
 */
public class RoleDaoImpl implements RoleDao{

    /**
     * 查询角色集合
     * @param connection 数据库连接
     * @return 角色集合
     * @throws Exception 抛出SQL异常
     */
    @Override
    public List<Role> getRoleList(Connection connection) throws Exception{
        List<Role> roleList = new ArrayList<>();
        if (connection != null) {
            PreparedStatement preparedStatement = null;
            ResultSet rs = null;
            String sql = "select * from smbms_role";
            rs = DBUtil.query(connection, preparedStatement, rs, sql ,null);
            while (rs.next()) {
                roleList.add(getRoleByResult(rs));
            }
            DBUtil.closeResource(preparedStatement, rs);
        }
        return roleList;
    }

    private Role getRoleByResult(ResultSet rs) throws Exception {
        Role role = new Role();
        role.setId(rs.getInt("id"));
        role.setRoleCode(rs.getString("roleCode"));
        role.setRoleName(rs.getString("roleName"));
        role.setCreatedBy(rs.getInt("createdBy"));
        role.setCreationDate(rs.getDate("creationDate"));
        role.setModifyBy(rs.getInt("modifyBy"));
        role.setModifyDate(rs.getDate("modifyDate"));
        return role;
    }

    @Test
    public void TestRoleList() {
        Connection connection = DBUtil.getConnection();
        try {
            List<Role> roleList = getRoleList(connection);
            for (Role role : roleList) {
                System.out.println(role);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(connection);
        }
    }
}
